package com.yuexunit.finance.project.action.v1.dto;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang3.StringUtils;

import com.yuexunit.core.BusinessException;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.common.util.BigDecimalUtils;
import com.yuexunit.finance.common.util.CollectionUtils;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.member.action.v1.model.SupplierInfo;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.member.entity.EnterpriseGradeEntity;
import com.yuexunit.finance.member.entity.FingerTrunkAccountMappingEntity;
import com.yuexunit.finance.member.entity.SupplierEntity;
import com.yuexunit.finance.member.service.EnterpriseGradeService;
import com.yuexunit.finance.member.service.EnterpriseService;
import com.yuexunit.finance.member.service.FingerTrunkAccountMappingService;
import com.yuexunit.finance.member.service.SupplierService;
import com.yuexunit.finance.project.action.v1.FinanceBulkstockActionApi;
import com.yuexunit.finance.project.action.v1.model.FinanceAudit;
import com.yuexunit.finance.project.action.v1.model.FinanceBulkstock;
import com.yuexunit.finance.project.action.v1.model.FinanceContainerBill;
import com.yuexunit.finance.project.action.v1.model.FinanceEvidentiary;
import com.yuexunit.finance.project.action.v1.model.FinanceEvidentiaryCategory;
import com.yuexunit.finance.project.action.v1.model.input.FinanceApplication;
import com.yuexunit.finance.project.action.v1.model.output.ContainerInventory;
import com.yuexunit.finance.project.action.v1.model.output.FinanceApplicationDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceAuditDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceCutLinesDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceFilesInfoDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceLineInfo;
import com.yuexunit.finance.project.action.v1.model.output.FinanceProcess;
import com.yuexunit.finance.project.action.v1.model.output.FinanceProcessDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceProductInnerDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceProductInterestItemDetail;
import com.yuexunit.finance.project.action.v1.model.output.FreightInfo;
import com.yuexunit.finance.project.action.v1.model.output.SupervisionEndallDetail;
import com.yuexunit.finance.project.entity.BillReceivableEntity;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceAuditEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockEntity;
import com.yuexunit.finance.project.entity.FinanceContainerBillEntity;
import com.yuexunit.finance.project.entity.FinanceContainerEntity;
import com.yuexunit.finance.project.entity.FinanceContractEntity;
import com.yuexunit.finance.project.entity.FinanceCutLinesEntity;
import com.yuexunit.finance.project.entity.FinanceEvidentiaryCategoryEntity;
import com.yuexunit.finance.project.entity.FinanceEvidentiaryEntity;
import com.yuexunit.finance.project.entity.FinanceFilesInfoEntity;
import com.yuexunit.finance.project.entity.FinanceMoneyStatementEntity;
import com.yuexunit.finance.project.entity.FinanceProcessDetailEntity;
import com.yuexunit.finance.project.entity.FinanceProcessEntity;
import com.yuexunit.finance.project.entity.FinanceProductInnerEntity;
import com.yuexunit.finance.project.entity.FinanceProductInterestItemEntity;
import com.yuexunit.finance.project.entity.FreightInfoEntity;
import com.yuexunit.finance.project.entity.LoanNoticeEntity;
import com.yuexunit.finance.project.entity.SupervisionEndallEntity;
import com.yuexunit.finance.project.entity.lexicon.ContainerSourceEnum;
import com.yuexunit.finance.project.entity.lexicon.DeliveryMethodEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceSegmentEnum;
import com.yuexunit.finance.project.entity.lexicon.ProductTypeEnum;
import com.yuexunit.finance.project.service.BillReceivableService;
import com.yuexunit.finance.project.service.FinanceApplicationService;
import com.yuexunit.finance.project.service.FinanceAuditService;
import com.yuexunit.finance.project.service.FinanceBulkstockService;
import com.yuexunit.finance.project.service.FinanceContainerBillService;
import com.yuexunit.finance.project.service.FinanceContainerService;
import com.yuexunit.finance.project.service.FinanceContractService;
import com.yuexunit.finance.project.service.FinanceEvidentiaryCategoryService;
import com.yuexunit.finance.project.service.FinanceEvidentiaryService;
import com.yuexunit.finance.project.service.FinanceFilesInfoService;
import com.yuexunit.finance.project.service.FinanceMoneyStatementService;
import com.yuexunit.finance.project.service.FinanceProcessDetailService;
import com.yuexunit.finance.project.service.FinanceProductInnerService;
import com.yuexunit.finance.project.service.FinanceProductInterestItemService;
import com.yuexunit.finance.project.service.FreightInfoService;
import com.yuexunit.finance.project.service.LoanNoticeService;
import com.yuexunit.finance.system.entity.SignFileInfoEntity;
import com.yuexunit.finance.system.service.SignFileInfoService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.util.DateUtil;
import com.yuexunit.util.StringUtil;

/**
 * @ClassName: FinanceApplicationCastor
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年9月24日 上午7:53:44
 */
public class FinanceApplicationCastor {
	// 收放款
	protected static LoanNoticeService loanNoticeService = ComponentFactory.loadClass(LoanNoticeService.class);	
	protected static FinanceAuditService financeAuditService = ComponentFactory.loadClass(FinanceAuditService.class);
	
	private static void perfectFinanceApplication(FinanceApplicationEntity entity, FinanceLineInfo info) {
		FinanceAuditService as = ComponentFactory.loadClass(FinanceAuditService.class);
		FinanceContractService financeContractService = ComponentFactory.loadClass(FinanceContractService.class);
		List<LoanNoticeEntity> ls = loanNoticeService.inquireLoanNoticeList(entity.getFinanceId());
		List<FinanceAuditEntity> fae=financeAuditService.inquireFinanceAuditList(entity.getFinanceId());
		BeanUtils.copyProperties(entity, info);
		//		info.setEstimateInterest(entity.getEstimateInterest().toString());
		info.setApplicationAmount(entity.getApplicationAmount().toString());
		//		info.setProductType(entity.getProductType().ordinal());
		info.setFinanceState(entity.getFinanceState().ordinal());
		info.setFinanceAmount(entity.getFinanceAmount().toString());
		info.setTotalLoanAmount(entity.getTotalLoanAmount().toString());
		info.setTotalReceivedAmount(entity.getTotalReceivedAmount().toString());
		info.setValuation(entity.getValuation().toString());
		info.setProductType(entity.getProductType().ordinal());
		//		info.setLoanMethod(entity.getLoanMethod().ordinal());
		info.setApplicationAmount(entity.getApplicationAmount().toString());
		for(LoanNoticeEntity lss:ls){
			if(lss.getLoanDate()!=null){
				String str=lss.getLoanDate().toString();
				StringBuffer s1=new StringBuffer(str);
		        s1.insert(4, "-");
		        s1.insert(7, "-");
				info.setLoanDate(s1.toString());
			}
			info.setLoanAmount(lss.getLoanAmount());
		}
		for(FinanceAuditEntity faes:fae){
			if(faes.getFinalState()!=null){
				info.setFinalState(faes.getFinalState().intValue());
			}
		}

		if(entity.getConstractState()!=null)
			info.setConstractState(entity.getConstractState().ordinal());
		FinanceAuditEntity fe = as.inquireLatestFinanceAudit(entity.getFinanceId());
		info.setCallback(Boolean.FALSE);
		if (null != fe) {
			info.setInterest(fe.getAuditInterest());
			info.setFinanceAuditId(as.inquireLatestFinanceAudit(entity.getFinanceId()).getFinanceAuditId());
			info.setCallback(fe.getCallback());
		}
		// 融资货物
		FinanceBulkstockService financeBulkstockService = ComponentFactory.loadClass(FinanceBulkstockService.class);
		List<FinanceBulkstockEntity> bulkstockList = financeBulkstockService.inquireFinanceBulkstockList(entity.getFinanceId());
		for (FinanceBulkstockEntity c : bulkstockList) {
			FinanceBulkstock bulkstock = BulkstockCastor.toFinanceBulkstock(c);
			info.getBulkstocks().add(bulkstock);
		}
		FinanceContractEntity fce = financeContractService.inquireFinanceIdContract(entity.getFinanceId(), null);
		info.setFinanceContractDetail(FinanceContractCastor.toFinanceContractDetail(fce));

		FinanceContractEntity fce1 = financeContractService.inquireFinanceIdContract(entity.getFinanceId(), 1);
		info.setFinanceProtocolDetail(FinanceContractCastor.toFinanceContractDetail(fce1));
		
		FinanceContractEntity fce2 = financeContractService.inquireFinanceIdContract(entity.getFinanceId(), 4);
		info.setSupplementContractDetail(FinanceContractCastor.toFinanceContractDetail(fce2));
	}

	/** 创建融资申请 */
	public static FinanceApplicationEntity fromFinanceApplication(FinanceApplication info) {
		EnterpriseEntity enterprise = null;
		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

		if (info.getFingerTrunkAccountId() != null && info.getFingerTrunkAccountId() != "") {
			FingerTrunkAccountMappingService fingerService = ComponentFactory.loadClass(FingerTrunkAccountMappingService.class);
			FingerTrunkAccountMappingEntity ftame =  fingerService.inquireFingerTrunkAccountMappingDetail(info.getFingerTrunkAccountId());
			enterprise = enterpriseService.inquireEnterpriseFromAccountId(ftame.getFinanceAccountId());
		} else {
			enterprise = enterpriseService.inquireEnterprise(FinanceSessionContext.getEnterpriseId());
		}

		if (enterprise == null) {
			throw new BusinessException("您还未登陆或系统中不存在该账号");
		}

		//申请金额须大于0元
		if (info.getApplicationAmount().intValue() == 0) {
			throw new BusinessException("融资申请金额必须大于0");
		}

		FinanceApplicationEntity entity = new FinanceApplicationEntity();
		BeanUtils.copyProperties(info, entity);
		entity.setValuation(new BigDecimal(info.getValuation()));
		entity.setEnterpriseId(enterprise.getEnterpriseId());
		entity.setEnterpriseName(enterprise.getEnterpriseName());

		//		FinanceProductService financeProductService = ComponentFactory.loadClass(FinanceProductService.class);
		//		FinanceProductEntity product = financeProductService.inquireFinanceProduct(info.getProductId());
		//		entity.setProductName(product.getProductName() + "(" + product.getProductNumber() + ")");
		//		entity.setProductType(product.getProductType());
		//		entity.setLoanMethod(product.getLoanMethod());
		//
		//		FinanceProductExpenseService financeProductExpenseService = ComponentFactory.loadClass(FinanceProductExpenseService.class);
		//		List<FinanceProductExpenseEntity> ahead = financeProductExpenseService.inquireFinanceProductExpense(info.getProductId(), ExpenseTypeEnum.AHEAD);
		//		int maxAhead = 0; // 提前还款期限
		//		for (FinanceProductExpenseEntity fpee : ahead) {
		//			maxAhead = fpee.getEndDay() > maxAhead ? fpee.getEndDay() : maxAhead;
		//		}
		//		entity.setAdvanceTimeLimit(maxAhead); // 提前还款期限
		//		Integer loanTimeLimit = info.getLoanTimeLimit() > product.getMaxDays() ? product.getMaxDays() : info.getLoanTimeLimit();
		//		entity.setLoanTimeLimit(loanTimeLimit); // 借款期限
		//		List<FinanceProductExpenseEntity> delay = financeProductExpenseService.inquireFinanceProductExpense(info.getProductId(), ExpenseTypeEnum.DELAY);
		//		int distrainMaxDays = 0; // 罚息时长
		//		for (FinanceProductExpenseEntity fpee : delay) {
		//			distrainMaxDays = fpee.getEndDay() > distrainMaxDays ? fpee.getEndDay() : distrainMaxDays;
		//		}
		//		// 罚息限制天数
		//		entity.setPunishTimeLimit(distrainMaxDays - product.getDistrain());
		//		if (entity.getPunishTimeLimit() < 0) {
		//			entity.setPunishTimeLimit(0);
		//			entity.setDistrainTimeLimit(distrainMaxDays);
		//		} else {
		//			// 赎货限制天数
		//			entity.setDistrainTimeLimit(product.getDistrain());
		//		}

		entity.setBookingSpace(Boolean.FALSE);
		if (StringUtils.isNoneBlank(info.getBookingSpaceNumber()) || info.getDeliveryMethod() != null || info.getDeclaredValue() != null) {
			entity.setBookingSpace(true);
			FinanceContainerEntity financeContainer = new FinanceContainerEntity();
			financeContainer.setBookingSpaceNumber(info.getBookingSpaceNumber());
			financeContainer.setDeliveryMethod(DeliveryMethodEnum.valueOf(info.getDeliveryMethod()));
			if (info.getDeclaredValue() == null) {
				info.setDeclaredValue(BigDecimal.ZERO);
			}
			financeContainer.setDeclaredValue(info.getDeclaredValue());
			financeContainer.setEnterpriseId(entity.getEnterpriseId());
			financeContainer.setEnterpriseName(entity.getEnterpriseName());
			entity.setFinanceContainer(financeContainer);
		}
		return entity;
	}
	
	/**代理创建融资申请 */
	public static FinanceApplicationEntity proxyFromFinanceApplication(FinanceApplication info) {
		EnterpriseEntity enterprise = null;
		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

		if (info.getFingerTrunkAccountId() != null && info.getFingerTrunkAccountId() != "") {
			FingerTrunkAccountMappingService fingerService = ComponentFactory.loadClass(FingerTrunkAccountMappingService.class);
			FingerTrunkAccountMappingEntity ftame =  fingerService.inquireFingerTrunkAccountMappingDetail(info.getFingerTrunkAccountId());
			enterprise = enterpriseService.inquireEnterpriseFromAccountId(ftame.getFinanceAccountId());
		} else {
			enterprise = enterpriseService.inquireEnterprise(info.getEnterpriseId());
		}

		if (enterprise == null) {
			throw new BusinessException("您还未登陆或系统中不存在该账号");
		}

		//申请金额须大于0元
		if (info.getApplicationAmount().intValue() == 0) {
			throw new BusinessException("融资申请金额必须大于0");
		}

		FinanceApplicationEntity entity = new FinanceApplicationEntity();
		BeanUtils.copyProperties(info, entity);
		entity.setValuation(new BigDecimal(info.getValuation()));
		entity.setEnterpriseId(enterprise.getEnterpriseId());
		entity.setEnterpriseName(enterprise.getEnterpriseName());

		//		FinanceProductService financeProductService = ComponentFactory.loadClass(FinanceProductService.class);
		//		FinanceProductEntity product = financeProductService.inquireFinanceProduct(info.getProductId());
		//		entity.setProductName(product.getProductName() + "(" + product.getProductNumber() + ")");
		//		entity.setProductType(product.getProductType());
		//		entity.setLoanMethod(product.getLoanMethod());
		//
		//		FinanceProductExpenseService financeProductExpenseService = ComponentFactory.loadClass(FinanceProductExpenseService.class);
		//		List<FinanceProductExpenseEntity> ahead = financeProductExpenseService.inquireFinanceProductExpense(info.getProductId(), ExpenseTypeEnum.AHEAD);
		//		int maxAhead = 0; // 提前还款期限
		//		for (FinanceProductExpenseEntity fpee : ahead) {
		//			maxAhead = fpee.getEndDay() > maxAhead ? fpee.getEndDay() : maxAhead;
		//		}
		//		entity.setAdvanceTimeLimit(maxAhead); // 提前还款期限
		//		Integer loanTimeLimit = info.getLoanTimeLimit() > product.getMaxDays() ? product.getMaxDays() : info.getLoanTimeLimit();
		//		entity.setLoanTimeLimit(loanTimeLimit); // 借款期限
		//		List<FinanceProductExpenseEntity> delay = financeProductExpenseService.inquireFinanceProductExpense(info.getProductId(), ExpenseTypeEnum.DELAY);
		//		int distrainMaxDays = 0; // 罚息时长
		//		for (FinanceProductExpenseEntity fpee : delay) {
		//			distrainMaxDays = fpee.getEndDay() > distrainMaxDays ? fpee.getEndDay() : distrainMaxDays;
		//		}
		//		// 罚息限制天数
		//		entity.setPunishTimeLimit(distrainMaxDays - product.getDistrain());
		//		if (entity.getPunishTimeLimit() < 0) {
		//			entity.setPunishTimeLimit(0);
		//			entity.setDistrainTimeLimit(distrainMaxDays);
		//		} else {
		//			// 赎货限制天数
		//			entity.setDistrainTimeLimit(product.getDistrain());
		//		}

		entity.setBookingSpace(Boolean.FALSE);
		if (StringUtils.isNoneBlank(info.getBookingSpaceNumber()) || info.getDeliveryMethod() != null || info.getDeclaredValue() != null) {
			entity.setBookingSpace(true);
			FinanceContainerEntity financeContainer = new FinanceContainerEntity();
			financeContainer.setBookingSpaceNumber(info.getBookingSpaceNumber());
			financeContainer.setDeliveryMethod(DeliveryMethodEnum.valueOf(info.getDeliveryMethod()));
			if (info.getDeclaredValue() == null) {
				info.setDeclaredValue(BigDecimal.ZERO);
			}
			financeContainer.setDeclaredValue(info.getDeclaredValue());
			financeContainer.setEnterpriseId(entity.getEnterpriseId());
			financeContainer.setEnterpriseName(entity.getEnterpriseName());
			entity.setFinanceContainer(financeContainer);
		}
		return entity;
	}

	public static List<FinanceContainerBillEntity> fromFinanceApplicationContainerBill(FinanceApplication params) {
		List<FinanceContainerBillEntity> bills = new ArrayList<>();
		if (params.getModel() == null || params.getModel().length <= 0) {
			return bills;
		}
		for (int i = 0; i < params.getModel().length; i++) {
			FinanceContainerBillEntity bill = new FinanceContainerBillEntity();
			bill.setDimension(CollectionUtils.getArrayIndexValue(params.getDimension(), i));
			bill.setEmptyWeight(CollectionUtils.getArrayIndexValue(params.getEmptyWeight(), i));
			bill.setModel(CollectionUtils.getArrayIndexValue(params.getModel(), i));
			bill.setQuantity(CollectionUtils.getArrayIndexValue(params.getQuantity(), i));
			bill.setContainerSource(ContainerSourceEnum.ENTERPRISE);
			bill.setSoc(BooleanUtils.toBoolean(CollectionUtils.getArrayIndexValue(params.getSoc(), i)));
			bills.add(bill);
		}
		return bills;
	}

	/** 融资明细 */
	public static FinanceApplicationDetail toFinanceApplicationDetail(FinanceApplicationEntity entity) {
		EnterpriseGradeService enterpriseGradeService = ComponentFactory.loadClass(EnterpriseGradeService.class);
		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(entity.getEnterpriseId());
		List<LoanNoticeEntity> ls = loanNoticeService.inquireLoanNoticeList(entity.getFinanceId());
		FinanceProductInnerService financeProductInnerService = ComponentFactory.loadClass(FinanceProductInnerService.class);
		FinanceProductInterestItemService financeProductInterestItemService = ComponentFactory.loadClass(FinanceProductInterestItemService.class);
//		ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		FinanceBulkstockActionApi financeBulkstockActionApi = ComponentFactory.loadClass(FinanceBulkstockActionApi.class);
		FinanceFilesInfoService financeFilesInfoService = ComponentFactory.loadClass(FinanceFilesInfoService.class);
		FreightInfoService freightInfoService = ComponentFactory.loadClass(FreightInfoService.class);
		SupplierService supplierService = ComponentFactory.loadClass(SupplierService.class);
		FinanceMoneyStatementService financeMoneyStatementService = ComponentFactory.loadClass(FinanceMoneyStatementService.class);
		BillReceivableService billReceivableService = ComponentFactory.loadClass(BillReceivableService.class);
		SignFileInfoService signFileInfoService = ComponentFactory.loadClass(SignFileInfoService.class);

//		PickupInventoryService pickupInventoryService = ComponentFactory.loadClass(PickupInventoryService.class);
//		List<Long> inventoryIds = pickupInventoryService.inquirePickupInventoryIdList(entity.getFinanceId());
		
		
		
		FinanceApplicationDetail detail = new FinanceApplicationDetail();
		perfectFinanceApplication(entity, detail);
		detail.setProductType(entity.getProductType().ordinal());
		detail.setAuditInterest(entity.getAuditInterest().toString());
		detail.setCreditQuota(grade.getCreditLine().toString());
		detail.setCreditQuotaConsume(grade.getCreditAlready());
		for(LoanNoticeEntity lss:ls){
			if(lss.getLoanDate()!=null){
				String str=lss.getLoanDate().toString();
				StringBuffer s1=new StringBuffer(str);
		        s1.insert(4, "-");
		        s1.insert(7, "-");
		        detail.setLoanDate(s1.toString());
			}
			detail.setLoanAmount(lss.getLoanAmount());
		}
		detail.setFinanceConstractState(entity.getFinanceConstractState().ordinal());

		//供应商信息-代采
		if (ProductTypeEnum.PURCHASING == entity.getProductType() || ProductTypeEnum.PURCHASING_STORAGE == entity.getProductType()) {
			SupplierEntity se = supplierService.inquireSupplierDetail(entity.getReceive());
			SupplierInfo si = new SupplierInfo();
			BeanUtils.copyProperties(se, si);
			detail.setSupplier(si);
		}

		// 融资证明材料
		FinanceEvidentiaryCategoryService financeEvidentiaryCategoryService = ComponentFactory.loadClass(FinanceEvidentiaryCategoryService.class);
		FinanceEvidentiaryService financeEvidentiaryService = ComponentFactory.loadClass(FinanceEvidentiaryService.class);
		List<FinanceEvidentiaryCategoryEntity> categoryList = financeEvidentiaryCategoryService.inquireFinanceEvidentiaryCategoryList(entity.getFinanceId());
		for (FinanceEvidentiaryCategoryEntity c : categoryList) {
			FinanceEvidentiaryCategory category = new FinanceEvidentiaryCategory();
			category.setEvidentiaryCategoryId(c.getEvidentiaryCategoryId());
			category.setTemplateId(c.getTemplateId());
			category.setCheckedRequired(c.getCheckedRequired().ordinal());
			category.setTemplateName(c.getTemplateName());
			List<FinanceEvidentiaryEntity> evidentiaryList = financeEvidentiaryService.inquireCategoryEvidentiaryList(c.getEvidentiaryCategoryId());
			for (FinanceEvidentiaryEntity e : evidentiaryList) {
				FinanceEvidentiary evidentiary = new FinanceEvidentiary();
				evidentiary.setEvidentiaryId(e.getEvidentiaryId());
				evidentiary.setMaterialFileuuid(e.getMaterialFileuuid());
				category.getEvidentiarys().add(evidentiary);
			}
			detail.getEvidentiaryCategorys().add(category);
		}
		if (entity.getBookingSpace()) {
			FinanceContainerService financeContainerService = ComponentFactory.loadClass(FinanceContainerService.class);
			FinanceContainerEntity financeContainer = financeContainerService.inquireFinanceContainer(entity.getFinanceId());
			if (financeContainer != null) {
				detail.setDeliveryMethod(financeContainer.getDeliveryMethod().ordinal());
				detail.setDeclaredValue(financeContainer.getDeclaredValue());
				detail.setBookingSpaceNumber(financeContainer.getBookingSpaceNumber());
				detail.setCaseQuantity(financeContainer.getCaseQuantity());
			}
		}
		FinanceContainerBillService financeContainerBillService = ComponentFactory.loadClass(FinanceContainerBillService.class);
		List<FinanceContainerBillEntity> containerBills = financeContainerBillService.inquireFinanceContainerBillList(entity.getFinanceId());
		for (FinanceContainerBillEntity fcbe : containerBills) {
			FinanceContainerBill fcb = new FinanceContainerBill();
			BeanUtils.copyProperties(fcbe, fcb);
			fcb.setContainerSource(fcbe.getContainerSource().ordinal());
			detail.getContainerBills().add(fcb);
//			detail.setQuantity(fcbe.getQuantity());
		}

		// 评审信息
		FinanceAuditService financeAuditService = ComponentFactory.loadClass(FinanceAuditService.class);
		FinanceAuditEntity financeAudit = financeAuditService.inquireLatestFinanceAudit(detail.getFinanceId());
		if (financeAudit != null) {
			FinanceAuditDetail auditDetail = new FinanceAuditDetail();
			BeanUtils.copyProperties(financeAudit, auditDetail);
			if(financeAudit.getBail()!=null)
				auditDetail.setBail(financeAudit.getBail().toString());
			if(financeAudit.getFinanceAmount()!=null)
				auditDetail.setFinanceAmount(financeAudit.getFinanceAmount().toString());
			if (financeAudit.getInsurance() == Boolean.TRUE) {
				auditDetail.setInsurance(1);
			} else {
				auditDetail.setInsurance(0);
			}
			detail.setFinanceAuditDetail(auditDetail);
		}

		//融资产品信息
		FinanceProductInnerEntity innerEntity = financeProductInnerService.inquireFinanceProductInner(entity.getFinanceId(), null);
		if (innerEntity != null) {
			List<FinanceProductInterestItemEntity> interestItemList = financeProductInterestItemService.inquireFinanceProductInterestItemList(innerEntity.getFinanceProductId());
			FinanceProductInnerDetail fpid = new FinanceProductInnerDetail();
			BeanUtils.copyProperties(innerEntity, fpid);
			fpid.setProductType(innerEntity.getProductType().ordinal());
			List<FinanceProductInterestItemDetail> fpiids = new ArrayList<>();
			for (FinanceProductInterestItemEntity fpiie : interestItemList) {
				FinanceProductInterestItemDetail fpiid = new FinanceProductInterestItemDetail();
				BeanUtils.copyProperties(fpiie, fpiid);
				fpiid.setBillingMethod(fpiie.getBillingMethod().ordinal());
				fpiids.add(fpiid);
			}
			fpid.setFinanceProductInterestItemList(fpiids);
			detail.setFinanceProductInnerDetail(fpid);
		} else {
			detail.setFinanceProductInnerDetail(new FinanceProductInnerDetail());
		}

		if (StringUtil.isBlank(detail.getTotalExchangeAmount())) {
			detail.setTotalExchangeAmount("0");
		}

		//融资货箱信息
//		List<ContainerInventoryEntity> containerList = containerInventoryService.inquireContainerInventoryList(entity.getFinanceId(), null);
		List<ContainerInventory> resultList = financeBulkstockActionApi.inquireFinanceContainerInventoryList(null, null, entity.getFinanceId(), null, null);
//		for (ContainerInventoryEntity cie : containerList) {
//			resultList.add(BulkstockCastor.toContainerInventory(cie, Boolean.FALSE));
//		}
		detail.setContainerInventoryList(resultList);

		//融资附件列表
		List<FinanceFilesInfoEntity> ffies = financeFilesInfoService.inquireFinanceFilesInfoList(entity.getFinanceId(), null);
		List<FinanceFilesInfoDetail> ffids = new ArrayList<>();
		for (FinanceFilesInfoEntity ffie : ffies) {
			if (StringUtil.isNotBlank(ffie.getFilesUuid())) {
				FinanceFilesInfoDetail ffid = new FinanceFilesInfoDetail();
				BeanUtils.copyProperties(ffie, ffid);
				StringBuffer sb = new StringBuffer();
				for (String s : ffie.getFilesUuid().split(",")) {
					SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(s);
					if (sfie == null) {
						continue;
					}
					sb.append(sfie.getFileSignState().ordinal() + ",");
				}
				if (sb != null && sb.length() > 0) {
					sb = sb.deleteCharAt(sb.length() - 1);
				}
				ffid.setFileSignState(sb.toString());
				ffids.add(ffid);
			}
		}
		detail.setFinanceFilesInfoList(ffids);

		//发票信息列表
		List<FreightInfoEntity> fies = freightInfoService.inquireFreightInfoList(entity.getFinanceId());
		List<FreightInfo> fis = new ArrayList<>();
		for (FreightInfoEntity fie : fies) {
			FreightInfo fi = new FreightInfo();
			BeanUtils.copyProperties(fie, fi);
			fis.add(fi);
		}
		detail.setFreightInfoList(fis);

		String[] statementSource = { "FINANCE_AUDIT", "BAIL_ADDITION" };
		FinanceMoneyStatementEntity statement = financeMoneyStatementService.inquireFinanceMoneyStatementDetail1(statementSource, entity.getFinanceId());
		if ((statement != null) && (statement.getBillReceivableId() != null)) {
			BillReceivableEntity bre = billReceivableService.inquireBillReceivable(statement.getBillReceivableId());
			if (bre != null) {
				detail.setBailVoucher(bre.getFileUuid());
			}

		}

		return detail;
	}

	/** 融资明细 */
	public static PageList<FinanceLineInfo> toFinanceLineInfo(PageList<FinanceApplicationEntity> entityPages, PageCriteria page) {
		PageList<FinanceLineInfo> results = new PageList<>(page, entityPages.getTotalRecordCount());
		for (FinanceApplicationEntity entity : entityPages) {
			FinanceLineInfo info = new FinanceLineInfo();
			perfectFinanceApplication(entity, info);
			info.setFinanceConstractState(entity.getFinanceConstractState().ordinal());
			results.add(info);
		}
		return results;
	}
	
//	/** 融资明细 */
//	public static PageList<FinanceLineInfo> toFinanceLineInfos(PageList<LoanNoticeEntity> entityPages, PageCriteria page) {
//		PageList<FinanceLineInfo> results = new PageList<>(page, entityPages.getTotalRecordCount());
//		for (LoanNoticeEntity entity : entityPages) {
//			FinanceLineInfo info = new FinanceLineInfo();
//			perfectFinanceApplication(entity, info);
//			results.add(info);
//		}
//		return results;
//	}


	/** 融资审核信息 */
	public static FinanceAuditEntity fromFinanceAudit(FinanceAudit info, FinanceAuditEntity auditEntity) {
		FinanceAuditEntity entity = new FinanceAuditEntity();
		if (auditEntity != null) {
			BeanUtils.copyProperties(auditEntity, entity);
		}
		BeanUtils.copyProperties(info, entity, "businessAudit", "businessAuditState", "operationAudit", "operationAuditState", "financialAudit", "financialAuditState", "riskAudit", "riskAuditState", "riskMemberAudit",
				"riskMemberAuditState", "ceoAudit", "ceoAuditState", "finalAudit", "finalAuditState");
		entity.setAuditor(FinanceSessionContext.getAccountFullName());
		entity.setAuditorId(FinanceSessionContext.getAccountId());
		entity.setFinanceAmount(BigDecimalUtils.parser(info.getFinanceAmount()));
		entity.setAuditInterest(BigDecimalUtils.parser(info.getAuditInterest()));
		entity.setAuditDateTime(DateUtil.now());
		entity.setOpenQuota(BigDecimalUtils.parser(info.getOpenQuota()));
		entity.setBail(BigDecimalUtils.parser(info.getBail()));
		entity.setBasePrice(BigDecimalUtils.parser(info.getBasePrice()));
		entity.setEstimateIncome(BigDecimalUtils.parser(info.getEstimateIncome()));
		entity.setEstimateCost(BigDecimalUtils.parser(info.getEstimateCost()));
		entity.setEstimateProfit(BigDecimalUtils.parser(info.getEstimateProfit()));
		if(info.getInsurance() != null) {
			entity.setInsurance(BooleanUtils.toBoolean(info.getInsurance()));
		}
		return entity;
	}

	public static FinanceAuditDetail toFinanceAuditDetail(FinanceAuditEntity entity) {
		if (entity == null) {
			return new FinanceAuditDetail();
		}
		FinanceAuditDetail detail = new FinanceAuditDetail();
		BeanUtils.copyProperties(entity, detail);
		detail.setFinanceAmount(BigDecimalUtils.format(entity.getFinanceAmount()));
		detail.setAuditInterest(BigDecimalUtils.format(entity.getAuditInterest()));
		detail.setOpenQuota(BigDecimalUtils.format(entity.getOpenQuota()));
		detail.setBail(BigDecimalUtils.format(entity.getBail()));
		detail.setBasePrice(BigDecimalUtils.format(entity.getBasePrice()));
		detail.setEstimateIncome(BigDecimalUtils.format(entity.getEstimateIncome()));
		detail.setEstimateCost(BigDecimalUtils.format(entity.getEstimateCost()));
		detail.setEstimateProfit(BigDecimalUtils.format(entity.getEstimateProfit()));
		detail.setInsurance(BooleanUtils.toIntegerObject(entity.getInsurance()));
		// 评审材料
		detail.setMaterials(FinanceMaterialCastor.toSegmentMaterials(entity.getFinanceId(), entity.getFinanceAuditId(), FinanceSegmentEnum.AUDIT_DATA));

		// 融资货物
		FinanceBulkstockService financeBulkstockService = ComponentFactory.loadClass(FinanceBulkstockService.class);
		List<FinanceBulkstockEntity> bulkstockList = financeBulkstockService.inquireFinanceBulkstockList(entity.getFinanceId());
		for (FinanceBulkstockEntity c : bulkstockList) {
			FinanceBulkstock bulkstock = BulkstockCastor.toFinanceBulkstock(c);
			detail.getBulkstocks().add(bulkstock);
		}
		return detail;
	}

	public static FinanceProcess toFinanceProcess(FinanceProcessEntity entity) {
		FinanceProcess info = new FinanceProcess();
		BeanUtils.copyProperties(entity, info);
		info.setProcessSegment(entity.getProcessSegment().ordinal());
		info.setProcessType(entity.getProcessType().ordinal());
		info.setBusinessType(entity.getBusinessType() == null ? null : entity.getBusinessType().ordinal());
		info.setOperatorRole(entity.getOperatorRole().ordinal());

		FinanceProcessDetailService financeProcessDetailService = ComponentFactory.loadClass(FinanceProcessDetailService.class);
		List<FinanceProcessDetailEntity> processDetailList = financeProcessDetailService.inquireFinanceProcessDetailList(entity.getProcessId());
		for (FinanceProcessDetailEntity fpde : processDetailList) {
			FinanceProcessDetail detail = new FinanceProcessDetail();
			BeanUtils.copyProperties(fpde, detail);
			detail.setBusinessType(fpde.getBusinessType().ordinal());
			detail.setOperatorRole(fpde.getOperatorRole().ordinal());
			info.getDetails().add(detail);
		}
		return info;
	}

	/** 终结通知书 */
	public static SupervisionEndallDetail toSupervisionEndallDetail(SupervisionEndallEntity supervisionEndall) {
		SupervisionEndallDetail info = new SupervisionEndallDetail();
		BeanUtils.copyProperties(supervisionEndall, info);
		return info;
	}

	/** 融资下调详情 */
	public static FinanceCutLinesDetail toFinanceCutLinesDetail(FinanceCutLinesEntity entity) {
		FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(entity.getFinanceId());
		FinanceCutLinesDetail detail = new FinanceCutLinesDetail();
		BeanUtils.copyProperties(entity, detail);
		detail.setAuditState(entity.getAuditState().ordinal());
		if (finance != null) {
			detail.setEnterpriseName(finance.getEnterpriseName());
			detail.setFinanceNumber(finance.getFinanceNumber());
		}
		return detail;
	}
}
